package com.jinlejia.erp.ui.mine.sign;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.databinding.ActivityFieldSignInBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.RxUpLoad;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * 外勤打卡
 */
public class FieldSignInActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;
    private JSONObject jsonObject;
    private ActivityFieldSignInBinding binding;
    //用于保存拍照图片的uri
    private Uri mCameraUri;

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private String mCameraImagePath;

    // 是否是Android 10以上手机
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_field_sign_in);
        binding.setEvent(this);
        progressDialog = new ProgressDialog(this, "请稍等...");
        jsonObject = new JSONObject();
        jsonObject.put("longitude", getIntent().getDoubleExtra("lng", 0));
        jsonObject.put("latitude", getIntent().getDoubleExtra("lat", 0));
        jsonObject.put("position", getIntent().getStringExtra("cur_location"));
        binding.currentLocation.setText(getIntent().getStringExtra("cur_location"));
        binding.rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.work_radio) {
                    //上班
                    jsonObject.put("type", 1);
                } else {
                    //下班
                    jsonObject.put("type", 2);
                }
            }
        });
        binding.outReason.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 100 - s.length();
                binding.textCount.setText(number + "/100");
                selectionStart = binding.outReason.getSelectionStart();
                selectionEnd = binding.outReason.getSelectionEnd();
                if (temp.length() > 100) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    binding.outReason.setText(s);
                    binding.outReason.setSelection(tempSelection);//设置光标在最后
                }
            }
        });
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.submit:
                //提交
                if (!jsonObject.containsKey("type")) {
                    CustomToast.showToast(this, "请选择上班下班", 1500);
                } else if (!jsonObject.containsKey("outType")) {
                    CustomToast.showToast(this, "请选择外出事项", 1500);
                } else if (null == mCameraUri && mCameraImagePath == null) {
                    CustomToast.showToast(this, "请上传图片", 1500);
                } else {
                    progressDialog.show();
                    if (mCameraImagePath != null) {
                        compressWithRx(new File(mCameraImagePath));
                    } else if (mCameraUri != null) {
                        compressWithRx(uriToFile(mCameraUri, this));
                    }

                }
                break;
            case R.id.out_items:
                //外出事项
                Intent intent1 = new Intent(FieldSignInActivity.this, OutItemsActivity.class);
                startActivityForResult(intent1, 101);
                break;
            case R.id.reset_select:
                //重选
                useCamera();
                break;
            case R.id.camera:
                //选图
                useCamera();
                break;
            case R.id.site_img:
                //已选图
                Intent intent = new Intent(FieldSignInActivity.this, ZoomImageActivity.class);
                if (mCameraUri != null) {
                    intent.putExtra("img_url", mCameraUri.toString());
                } else if (mCameraImagePath != null) {
                    intent.putExtra("img_url", mCameraImagePath);
                }
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void submit() {


        if (!TextUtils.isEmpty(binding.outReason.getText())) {
            jsonObject.put("outReason", binding.outReason.getText());
        }

        OkHttpUtils.postString()
                .url(ApiConfig.FIELD_OUT_SIGN)
                .content(jsonObject.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        progressDialog.dismiss();
                        if (DataFilter.filter(FieldSignInActivity.this, response)) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }
                });

    }

    private void useCamera() {
        /*获取当前系统的android版本号*/
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File photoFile = null;
        Uri photoUri = null;
        if (isAndroidQ) {
            // 适配android 10
            photoUri = createImageUri();
        } else {
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (photoFile != null) {
                mCameraImagePath = photoFile.getAbsolutePath();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                    photoUri = FileProvider.getUriForFile(this, "com.jinlejia.erp.fileProvider", photoFile);
                } else {
                    photoUri = Uri.fromFile(photoFile);
                }
            }
        }
        if (photoUri != null) {
            mCameraUri = photoUri;
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivityForResult(intent, 100);
        }
    }

    /**
     * 压缩单张图片 RxJava 方式
     */
    private void compressWithRx(File file) {
        Luban.get(this)
                .load(file)
                .putGear(Luban.THIRD_GEAR)
                .asObservable()
                .flatMap(new Func1<File, Observable<String>>() {
                    @Override
                    public Observable<String> call(File file) {
                        Map<String, String> header = new HashMap<>();
                        header.put("token", ACache.get(FieldSignInActivity.this).getAsString("token") == null ? "" : ACache.get(FieldSignInActivity.this).getAsString("token"));
//                        header.put("cookie", ACache.get(InvestigationImageActivity.this).getAsString("cookie") == null ? "" : ACache.get(InvestigationImageActivity.this).getAsString("cookie"));
                        header.put("cookie", null == DbUtil.getDB(FieldSignInActivity.this).single().queryById(200, SaveCookieBean.class) ? "" : DbUtil.getDB(FieldSignInActivity.this).single().queryById(200, SaveCookieBean.class).getCookie());

                        return RxUpLoad.get(FieldSignInActivity.this)
                                .url(ApiConfig.IMG_UPLOAD)
                                .file(file)
                                .fileName(System.currentTimeMillis() + ".jpg")
                                .key("uploadFile")
                                .header(header)
                                .asObservable();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        JSONObject json = JSON.parseObject(s);
                        if (json.get("code").toString().equals("200")) {
                            jsonObject.put("sceneImgUrl", json.get("data"));
                            submit();
                        } else {
                            progressDialog.dismiss();
                            CustomToast.showToast(FieldSignInActivity.this, "图片上传失败，请重试!", 1500);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    if (mCameraUri != null) {
                        Glide.with(FieldSignInActivity.this)
                                .load(mCameraUri)
                                .into(binding.siteImg);

                    } else if (mCameraImagePath != null) {
                        Glide.with(FieldSignInActivity.this)
                                .load(mCameraImagePath)
                                .into(binding.siteImg);
                    } else {
                        CustomToast.showToast(FieldSignInActivity.this, "获取图片失败", 1500);
                        return;
                    }
                    binding.camera.setVisibility(View.GONE);
                    binding.siteImg.setVisibility(View.VISIBLE);
                    binding.resetSelect.setVisibility(View.VISIBLE);
                    break;
                case 101:
                    binding.outItems.setText(data.getStringExtra("name"));
                    jsonObject.put("outType", data.getStringExtra("value"));
                    break;
                default:
                    break;
            }

        }
    }


    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    /**
     * 创建保存图片的文件
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }


    public static File uriToFile(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

}
